<?php

namespace Sffi\ElementPlus\base;

trait EntityToArray
{
    public function __toArray(): array
    {
        $reflection = new \ReflectionClass($this);
        $properties = $reflection->getProperties();
        $res = [];
        foreach ($properties as $property) {
            if ($property->isStatic()) {
                continue;
            }
            $property->setAccessible(true);
            if ($property->isInitialized($this)) {
                $value = $property->getValue($this);
                if (!$value && $value!==0) {
                    continue;
                }
                if (is_array($value)) {
                    $newValue = [];
                    foreach ($value as $key => $item) {
                        if (is_object($item) && method_exists($item, '__toArray')){
                            $newValue[$key] = $item->__toArray();
                        }else{
                            $newValue[$key] = $item;
                        }
                    }
                }
                $res[$property->getName()] = $newValue ?? (is_numeric($value) ? (int)$value : $value);
                unset($newValue);
            }
        }
        return $res;
    }
}